package com.cym.controller;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.ModelAndView;

import com.cym.model.Project;
import com.cym.model.User;
import com.cym.service.UserService;
import com.cym.utils.BaseController;
import com.cym.utils.JsonResult;

/**
 * 登录页
 * 
 * @author Useristrator
 *
 */
@Mapping("/adminPage/login")
@Controller
public class LoginController extends BaseController {
	@Inject
	UserService userService;

	@Mapping("")
	public ModelAndView user(ModelAndView modelAndView) {
		List<Project> projectList = sqlHelper.findAll(Project.class);

		projectList.add(buildSystemProject());

		modelAndView.put("projectList", projectList);
		modelAndView.view("/adminPage/login/index.html");
		return modelAndView;
	}

	@Mapping(value = "login")
	public JsonResult submitLogin(String name, String pass, String projectId) {
		User user = userService.login(name, pass);
		if (user == null) {
			return renderError("登录失败,请检查用户名密码");
		}
		if (user.getStatus() == 1) {
			return renderError("该用户已被禁用");
		}
		
		if (!userService.hasProject(user.getId(), projectId)) {
			return renderError("你没有这个项目的权限");
		}
		
		Project project = sqlHelper.findById(projectId, Project.class);
		if (project != null && project.getStatus() == 1) {
			return renderError("该项目已被禁用");
		}

		Context.current().sessionSet("user", user);

		if (projectId.equals("system")) {
			Context.current().sessionSet("project", buildSystemProject());
		} else {
			Context.current().sessionSet("project", sqlHelper.findById(projectId, Project.class));
		}
		return renderSuccess();
	}

	private Project buildSystemProject() {
		Project project = new Project();
		project.setId("system");
		project.setName("系统管理");

		return project;
	}

	@Mapping(value = "changePass")
	public JsonResult changePass(String userName, String userPass, String newPass) {
		User user = userService.login(userName, userPass);
		if (user == null) {
			return renderError("旧密码错误");
		}

		if (user != null) {
			user.setPass(newPass);
			sqlHelper.updateById(user);
		}

		return renderSuccess();
	}

	@Mapping("loginOut")
	public void loginOut(Context ctx) {
		ctx.sessionRemove("user");
		ctx.sessionRemove("project");
		ctx.redirect("/adminPage/login");
	}

}
